<?php
/**
 * 问题控制器类
 */
namespace Home\Controller;
use Think\Controller;

class QuestionController extends CommonController
{
    // 网站首页问题列表
    public function index()
    {
        echo "here is QuestionController";
    }
    // 全部问题列表
    public function qlistall()
    {
        $sql = "select t4.uid,t4.uname,t5.avatar,t1.qid,t1.title,t1.qtime,t3.category,t2.num_of_ans,t2.views,t2.close,t2.excellent,t2.top from question t1 left join question_ext t2 on t1.qid=t2.qid left join qcategory t3 on t1.cag_id=t3.cag_id left join users t4 on t1.uid=t4.uid left join users_ext t5 on t1.uid=t5.uid order by t2.top,t1.qid desc";
        $nowpage = I('get.page', 1, 'intval');
        $list = $this->getPage($sql, $nowpage);// 获取分页
        $this->assign('list', $list['page_list']);// 赋值数据集
        $this->assign('nowpage', $nowpage);// 赋值当前页码
        $this->assign('allpages', $list['allpages']);// 赋值总页码
        $this->assign('actname', ACTION_NAME);
        $this->assign('title', '全部 - Fly社区');
        $this->display();
    }
    // 未结帖问题列表
    public function qlistunsolved()
    {
        $sql = "select t4.uid,t4.uname,t5.avatar,t1.qid,t1.title,t1.qtime,t3.category,t2.num_of_ans from question t1 left join question_ext t2 on t1.qid=t2.qid left join qcategory t3 on t1.cag_id=t3.cag_id left join users t4 on t1.uid=t4.uid left join users_ext t5 on t1.uid=t5.uid where t2.close='0' order by t2.top,t1.qid desc";
        $nowpage = I('get.page', 1, 'intval');
        $list = $this->getPage($sql, $nowpage);// 获取分页
        $this->assign('list', $list['page_list']);// 赋值数据集
        $this->assign('nowpage', $nowpage);// 赋值当前页码
        $this->assign('allpages', $list['allpages']);// 赋值总页码
        $this->assign('actname', ACTION_NAME);
        $this->assign('title', '未结帖 - Fly社区');
        $this->display();
    }
    // 已采纳问题列表
    public function qlistsolved()
    {
        $sql = "select t4.uid,t4.uname,t5.avatar,t1.qid,t1.title,t1.qtime,t3.category,t2.num_of_ans from question t1 left join question_ext t2 on t1.qid=t2.qid left join qcategory t3 on t1.cag_id=t3.cag_id left join users t4 on t1.uid=t4.uid left join users_ext t5 on t1.uid=t5.uid where t2.close='1' order by t2.top,t1.qid desc";
        $nowpage = I('get.page', 1, 'intval');
        $list = $this->getPage($sql, $nowpage);// 获取分页
        $this->assign('list', $list['page_list']);// 赋值数据集
        $this->assign('nowpage', $nowpage);// 赋值当前页码
        $this->assign('allpages', $list['allpages']);// 赋值总页码
        $this->assign('actname', ACTION_NAME);
        $this->assign('title', '已采纳 - Fly社区');
        $this->display();
    }
    // 精帖问题列表
    public function qlistwonderful()
    {
        $sql = "select t4.uid,t4.uname,t5.avatar,t1.qid,t1.title,t1.qtime,t3.category,t2.num_of_ans from question t1 left join question_ext t2 on t1.qid=t2.qid left join qcategory t3 on t1.cag_id=t3.cag_id left join users t4 on t1.uid=t4.uid left join users_ext t5 on t1.uid=t5.uid where t2.excellent='1' order by t2.top,t1.qid desc";
        $nowpage = I('get.page', 1, 'intval');
        $list = $this->getPage($sql, $nowpage);// 获取分页
        $this->assign('list', $list['page_list']);// 赋值数据集
        $this->assign('nowpage', $nowpage);// 赋值当前页码
        $this->assign('allpages', $list['allpages']);// 赋值总页码
        $this->assign('actname', ACTION_NAME);
        $this->assign('title', '精帖 - Fly社区');
        $this->display();
    }
    // 我的帖问题列表
    public function qlistuser()
    {
        redirect(U('home/ucenter/center'));
    }
    // 问题提交页面
    public function qsubmit()
    {
        $this->assign('title', '发表问题 - Fly社区');
        $cateData = M('qcategory')->select();
        $cateData = $this->cateTree($cateData);
        $question = D('vercode')->getOne();
        $this->assign('question', $question);
        $this->assign('cateData', $cateData);
        $this->display();
    }
    // 问题图片上传方法
    public function qimgupload()
    {
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     52428800 ;// 设置附件上传大小
        $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath  =     './Public/images/qimg/'; // 设置附件上传根目录
        $upload->savePath  =     ''; // 设置附件上传（子）目录
        // 上传文件 
        $info   =   $upload->upload();

        if(!$info) {// 上传错误提示错误信息
            $retrunData = array(
                'code'=>1,
                'msg'=>$upload->getError()
            );
            echo json_encode($retrunData);
        }else{// 上传成功
            $info = current($info);
            $retrunData = array(
                'code'=>0,
                'msg'=>'上传成功',
                'data'=>array(
                    'src'=>__ROOT__.'/Public/images/qimg/'.$info['savepath'].$info['savename'],
                    'title'=>'图片'
                    )
                );
            echo json_encode($retrunData);
        }
    }
    // 问题上传方法
    public function qpost()
    {
        $this->checkVercode();
        $get_data = I('post.');//获取post数据
        unset($get_data['file']);//去除永不到的file键值
        unset($get_data['vercode']);//去除无用验证码
        $get_data['uid'] = $_SESSION['uid'];
        $get_data['qext'] = array('views' => '0');
        $get_data['qtime'] = time();
        $res = D("question")->relation(true)->add($get_data);
        if ($res) {
            unset($_SESSION['answer']);//清除验证答案
            $data = array('info'=>'问题发布完成，等待跳转。',
                          'url'=>U('home/question/qpage').'/qid/'.$res);
            echo json_encode($data);
        } else {
            $data = array('error'=>'因未知原因，问题发布失败。');
            echo json_encode($data);
        }
    }
    // 问题详细页面
    public function qpage()
    {
        $get_data = I('get.');
        $qcondition = array('qid'=>$get_data['qid']);
        $q_data = D("Question")->where($qcondition)->relation(true)->find();

        $acondition = array('qid'=>$get_data['qid']);
        $a_data_tmp = $this->ansPage($acondition);
        $a_data = $a_data_tmp['page_list'];
        $allpages = $a_data_tmp['allpages'];
        $nowpage = $a_data_tmp['nowpage'];
        $ucondition = array('uid'=>$q_data['uid']);
        $u_data = D("Users")->where($ucondition)->relation(true)->find();
        
        if ($q_data) {
            $condition = array('qid'=>$get_data['qid']);
            $data['views'] = $q_data['qext']['views']+1;
            M("question_ext")->where($condition)->save($data);
            $viewsRank = $this->viewsRank();
            $ansnumRank = $this->ansnumRank();
            $this->assign('title', $q_data['title']);
            $this->assign('q_data', $q_data);
            $this->assign('u_data', $u_data);
            $this->assign('a_data', $a_data);
            $this->assign('allpages', $allpages);
            $this->assign('nowpage', $nowpage);
            $this->assign('viewsRank', $viewsRank);
            $this->assign('ansnumRank', $ansnumRank);
            $this->display();
        } else {
            $this->error('该问题不存在，等待返回首页', U('/home/index/index'), 3);
            exit;
        }
    }
    // 分页
    public function ansPage($acondition = '')
    {
        $list_rows = 5;
        $get_post = I('post.');
        if (empty($get_post)) {
            $apage = 1;//当前页码
            $result = D("Answer")->where($acondition)->relation(true)->order('is_great desc,atime desc')->select();
            $page_list = D("Answer")->where($acondition)->relation(true)->order('is_great desc,atime desc')->page(1, $list_rows)->select();
            $count = count($result);// 查询记录总数
            $allpages = ceil($count / $list_rows);// 获取总页面数
            return ['allpages'=>$allpages,'nowpage'=>$apage,'page_list'=>$page_list];
        } else {
            $acondition = array('qid'=>$get_post['qid']);
            $apage = $get_post['apage'];
            $result = D("Answer")->where($acondition)->relation(true)->order('is_great desc,atime desc')->select();
            $count = count($result);// 查询记录总数
            $allpages = ceil($count / $list_rows);// 获取总页面数
            $page_list = D("Answer")->where($acondition)->relation(true)->order('is_great desc,atime desc')->page($apage, $list_rows)->select();//获取分页
            $str = '';
            foreach ($page_list as $value) {
                $str .= '<li class="jieda-daan"data-id="'.$value['aid'].'"><a name="item-1476470300661"></a><div class="detail-about detail-about-reply"><a href="'.U('home/ucenter/index', array('uid'=>$value['uid'])).'"class="jie-user"><img alt="'.$value['user']['uname'].'"src="ROOT/'.$value['uext']['avatar'].'"layer-index="1"><cite><i>'.$value['user']['uname'].'</i></cite></a><div class="detail-hits"><span>'.timeFormat($value['atime']).'</span></div>';
                if ($value['is_great'] == 1) {
                    $str .= '<i title="最佳答案" class="iconfont icon-caina"></i>';
                }
                $str .= '</div><div class="detail-body jieda-body">'.htmlspecialchars_decode($value['content']).'</div><div class="jieda-reply"><span type="zan"class="jieda-zan zaned"><i class="iconfont icon-zan"></i><em>'.$value['aext']['praise'].'</em></span><span type="reply"><i class="iconfont icon-svgmoban53"></i>回复</span>';
                if ($value['uid']!=$_SESSION['uid']&&$_SESSION['uid']==$value['q']['uid']&&$value['qext']['close'] == 0) {
                    $str .= '<div class="jieda-admin"><span class="jieda-accept"type="accept">采纳</span></div>';
                }
                $str .= '</div></li>';// 输出html文本
            }
            echo json_encode(['page_list'=>$str]);
        }
    }
}
